﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using Moonwish.Core;
using Moonwish.Core.EntityCore;
using Moonwish.Core.DataAccess;
using Moonwish.Foundation.DataEntity;

namespace Moonwish.Foundation.DataAccess.SqlServer.ValueObjectClassCmd
{
    public class QueryDataCommand : QueryCommand<V_FDT_ValueObjectClass>
    {
        public QueryDataCommand(DbContext dbContext, Request request) : base(dbContext, request)
        {
            Map.Add("ValueObjectClass.Id".ToLower(), "ValueObjectClassId");
            Map.Add("ValueObjectClass.Name".ToLower(), "Name");
            Map.Add("ValueObjectClass.Code".ToLower(), "Code");
            Map.Add("ValueObjectClass.Status".ToLower(), "DataStatus");
        }

        public override List<V_FDT_ValueObjectClass> Execute()
        {
            var classData = DbContext.Set<V_FDT_ValueObjectClass>().SqlQuery(BuildSql()).ToList();
            
            if (classData.Count > 0)
            {
                var quicklyClassData = classData.ToDictionary(item => item.ValueObjectClassId);

                var ids = classData.Select(obj => obj.ValueObjectClassId).ToList();

                // 查询值对象，构建分类的子集合。
                var valueObjectData = DbContext.Set<V_FDT_ValueObject>().SqlQuery(
                        String.Format(
                            "select * from [V_FDT_ValueObject] t where t.ValueObjectClassId in ('{0}')",
                            String.Join("','", ids)));
                foreach (var item in valueObjectData)
                {
                    quicklyClassData[item.ValueObjectClassId].V_FDT_ValueObjects.Add(item);
                }
            }
            return classData;
        }

        protected override string BuildSql()
        {
            var sql = new StringBuilder();
            sql.Append("select * from [V_FDT_ValueObjectClass] t where 1 = 1 ");
            if (Request.Items != null)
            {
                foreach (var item in Request.Items)
                {
                    if (String.IsNullOrEmpty(item.FieldName))
                    {
                        throw new InvalidOperationException("查询条件的字段名称不能为空。");
                    }
                    if (item.Values == null || item.Values.Length == 0)
                    {
                        throw new InvalidOperationException("查询条件的值不能为空。");
                    }
                    string column = ToDbColumn(item.FieldName.ToLower());
                    sql.Append(String.Format(" {0} {1} {2} {3} ", item.Relation, column, item.GetOperator(), item.GetValues()));
                }
            }
            return sql.ToString();
        }
    }
}
